package com.java1234.view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;

import com.java1234.dao.IBookDao;
import com.java1234.dao.IBorrowDao;
import com.java1234.dao.IBorrowerDao;
import com.java1234.dao.ILibrarianDao;
import com.java1234.dao.impl.BookImpl;
import com.java1234.dao.impl.BorrowImpl;
import com.java1234.dao.impl.BorrowerImpl;
import com.java1234.dao.impl.LibrarianImpl;
import com.java1234.model.Book;
import com.java1234.model.Borrow;
import com.java1234.util.DbUtil;
import com.java1234.util.StringUtil;

public class BookBorrowManageInterFrm extends JInternalFrame {// 功能实现，但可以增加图书id查询。borrower和borrow的关系就像bookType和book。
	private JTextField borrowerAccountTxt;
	private DbUtil dbUtil = new DbUtil();
	private ILibrarianDao librarianDao = new LibrarianImpl();
	private IBookDao bookDao = new BookImpl();
	private IBorrowerDao borrowerDao = new BorrowerImpl();

	private JTable bookBorrowTable;
	private IBorrowDao borrowDao = new BorrowImpl();
	private JTextField bookStatusTxt;
	private JTextField s_bookIdTxt;
	private JTextField bookIdTxt;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BookBorrowManageInterFrm frame = new BookBorrowManageInterFrm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public BookBorrowManageInterFrm() {
		setClosable(true);
		setTitle("图书借阅");
		setBounds(100, 100, 757, 678);

		JLabel lblNewLabel = new JLabel("借阅者账号：");

		JLabel lblNewLabel_1 = new JLabel("图书编号：");

		borrowerAccountTxt = new JTextField();
		borrowerAccountTxt.setColumns(10);

		JButton btnNewButton_1 = new JButton("重置");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resetValueActionPerformed();
			}
		});

		JButton btnNewButton = new JButton("借阅");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				borrowActionPerformed(e);
			}
		});

		JScrollPane scrollPane = new JScrollPane();

		JLabel lblNewLabel_3 = new JLabel("图书状态：");

		bookStatusTxt = new JTextField();
		bookStatusTxt.setEditable(false);
		bookStatusTxt.setColumns(10);

		JLabel lblNewLabel_2 = new JLabel("图书编号：");

		s_bookIdTxt = new JTextField();
		s_bookIdTxt.setColumns(10);

		JButton btnNewButton_2 = new JButton("查询");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookIdSearchActionPerformed(e);
			}
		});
		
		bookIdTxt = new JTextField();
		bookIdTxt.setColumns(10);
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(74)
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(btnNewButton)
								.addComponent(lblNewLabel)
								.addComponent(lblNewLabel_3))
							.addGap(6))
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(lblNewLabel_1)
							.addGap(18)))
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
							.addGroup(groupLayout.createSequentialGroup()
								.addComponent(btnNewButton_1)
								.addContainerGap())
							.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
									.addComponent(bookIdTxt, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
									.addComponent(borrowerAccountTxt, GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE))
								.addGap(273)))
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(bookStatusTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addContainerGap())))
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap(34, Short.MAX_VALUE)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 674, GroupLayout.PREFERRED_SIZE)
					.addGap(33))
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(79)
					.addComponent(lblNewLabel_2)
					.addGap(32)
					.addComponent(s_bookIdTxt, GroupLayout.PREFERRED_SIZE, 236, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(btnNewButton_2)
					.addContainerGap(238, Short.MAX_VALUE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(37)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_2)
						.addComponent(s_bookIdTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnNewButton_2))
					.addGap(81)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 256, GroupLayout.PREFERRED_SIZE)
					.addGap(29)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblNewLabel)
						.addComponent(borrowerAccountTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(40)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_1)
						.addComponent(bookIdTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_3)
						.addComponent(bookStatusTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(29)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnNewButton)
						.addComponent(btnNewButton_1))
					.addGap(30))
		);

		bookBorrowTable = new JTable();
		bookBorrowTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				bookTypeTableMousePressed(e);
			}
		});
		bookBorrowTable.setModel(new DefaultTableModel(new Object[][] {},
				new String[] { "\u56FE\u4E66\u7F16\u53F7", "\u56FE\u4E66\u72B6\u6001" }) {
			boolean[] columnEditables = new boolean[] { false, false };

			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane.setViewportView(bookBorrowTable);
		getContentPane().setLayout(groupLayout);
		this.fillTable(new Borrow());
	}

	/**
	 * 初始化表格数据
	 * 
	 * @param book
	 */
	private void fillTable(Borrow borrow) {
		DefaultTableModel dtm = (DefaultTableModel) bookBorrowTable.getModel();
		dtm.setRowCount(0);// 设置成0行
		Connection con = null;
		try {
			con = dbUtil.getCon();
			ResultSet rs = borrowDao.list(con, borrow);
			while (rs.next()) {
				Vector v = new Vector();
				v.add(rs.getString("bookId"));
				v.add(rs.getString("bookStatus"));
				dtm.addRow(v);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 图书Id搜索事件处理
	 * 
	 * @param e
	 */
	private void bookIdSearchActionPerformed(ActionEvent evt) {
		String s_bookId = this.s_bookIdTxt.getText();
		Borrow borrow=new Borrow();
		borrow.setBookId(s_bookId);
		this.fillTable(borrow);
	}

	/**
	 * 表格行点击事件处理
	 * 
	 * @param e
	 */
	private void bookTypeTableMousePressed(MouseEvent evt) {
		int row = bookBorrowTable.getSelectedRow();
		bookIdTxt.setText((String) bookBorrowTable.getValueAt(row, 0));
		bookStatusTxt.setText((String) bookBorrowTable.getValueAt(row, 1));
	}

	/**
	 * 图书借阅事件处理
	 * 
	 * @param evt
	 */
	private void borrowActionPerformed(ActionEvent evt) {
		String bookId = this.bookIdTxt.getText();

		if (StringUtil.isEmpty(bookId)) {
			JOptionPane.showMessageDialog(null, "请选择要借的书");
			return;
		}
		String borrowerAccount = this.borrowerAccountTxt.getText();
		String bookStatus = this.bookStatusTxt.getText();

		if (StringUtil.isEmpty(borrowerAccount)) {
			JOptionPane.showMessageDialog(null, "未输入借阅者！");
			return;
		}
		if (StringUtil.isEmpty(bookId)) {
			JOptionPane.showMessageDialog(null, "未输入图书状态！");
			return;
		}

		Borrow borrow = new Borrow(borrowerAccount, bookId, bookStatus);

		Connection con = null;
		try {
			con = dbUtil.getCon();
			boolean flag = borrowerDao.existBorrowerByBorrowerAccount(con, borrowerAccount);
			if (flag == false) {
				JOptionPane.showMessageDialog(null, "当前借阅者账户下没有借阅者，不能借阅");
				return;
			}
			int addNum = borrowDao.update(con, borrow);
			if (addNum == 1 && borrow.getBookStatus().equals("在馆")) {
				JOptionPane.showMessageDialog(null, "借阅成功！");// 借出状态修改不了（没变化）解决方案：在impl里改set
				resetValueActionPerformed();
				this.fillTable(new Borrow());
				borrowDao.add(con, borrow);
			} else {
				JOptionPane.showMessageDialog(null, "当前图书已借出！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "借阅失败！");
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 重置事件处理
	 * 
	 * @param e
	 */
	private void resetValueActionPerformed() {
		this.borrowerAccountTxt.setText("");
		this.bookIdTxt.setText("");
		this.bookStatusTxt.setText("");
	}
}
